﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;
namespace DHQGHN.PM0.Controllers.Admin
{
    public class ResidentGroupController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ResidentGroupController));

        public ActionResult Index(ResidentGroupModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentID = null)
        {
            try
            {
                if (a == null) a = new ResidentGroupModel();
                if (string.IsNullOrEmpty(currentID)) currentID = string.Empty;

                var model = search(a, pageIndex, currentID, false);
                return View("~/Views/ResidentGroup/ResidentGroup.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới nhóm dân cư
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateResidentGroup(string id)
        {
            try
            {
                ResidentGroupModel model = null;
                if (!String.IsNullOrEmpty(id))
                {
                    ResidentGroupBO residentGroupBO = new ResidentGroupBO();
                    model = new ResidentGroupModel(residentGroupBO.GetResidentGroupId(id));
                }
                if (model == null)
                {
                    model = new ResidentGroupModel();
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/ResidentGroup/_ResidentGroupModel.cshtml", model);
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(ResidentGroupModel aModel = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string currentId = null)
        {
            try
            {
                if (aModel == null) aModel = new ResidentGroupModel();
                if (string.IsNullOrEmpty(currentId)) currentId = string.Empty;

                var model = search(aModel, pageIndex, currentId, false);
                return PartialView("~/Views/ResidentGroup/_ResidentGroupList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }
        /// Thêm mới dân cư
        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateResidentGroup(ResidentGroupModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    ResidentGroupBO residentGroupBO = new ResidentGroupBO();
                    bool result = residentGroupBO.createOrUpdateResidentGroup(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<ResidentGroupModel>(GetCurrentUserName(),
                          CommonData.AppName,
                          GetFunction(),
                          Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateResidentGroup", model);

                        if (!(String.IsNullOrEmpty(model.RESIDENT_GROUP_ID) || String.IsNullOrWhiteSpace(model.RESIDENT_GROUP_ID)))
                        {
                            return Json(JsonResponse.Json200("Cập nhật nhóm cư trú thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Thêm mới nhóm cư trú thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }
        ///-------------------------------------------------------------------------------
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    ResidentGroupBO residentGroupBO = new ResidentGroupBO();
                    bool result = residentGroupBO.deleteResidentGroup(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa nhóm cư trú thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<ResidentGroupModel> search(ResidentGroupModel aModel, int pageIndex, string currentId, bool compareEqual)
        {
            try
            {
                ResidentGroupBO residentGroupBO = new ResidentGroupBO();

                var DALModel = residentGroupBO.GetDynamicListPaging(aModel.toDALModel(), PageSize, pageIndex, compareEqual);
                var models = new DataPage<ResidentGroupModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.ResidentGroupModel residentGroup in lstItem)
                {
                    models.Data.Add(new ResidentGroupModel(residentGroup));
                }

                ResidentGroupModel model = null;
                if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
                {
                    model = models.Data.Find(user => Equals(user.RESIDENT_GROUP_ID, currentId));
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = aModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "ResidentGroup",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "residentgroup-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra tên nhóm dân cư đã tồn tại chưa
        public JsonResult CheckExistResidentGroupName(string name, string RESIDENT_GROUP_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(name))
                {

                    ResidentGroupModel residentGroupModel = new ResidentGroupModel()
                    {
                        NAME = name
                    };

                    var model = search(residentGroupModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {
                        var lstItem = model.Data;
                        foreach (ResidentGroupModel residentGroup in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(RESIDENT_GROUP_ID) || String.IsNullOrWhiteSpace(RESIDENT_GROUP_ID)))
                            {
                                if (!Equals(residentGroup.RESIDENT_GROUP_ID, RESIDENT_GROUP_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.ResidentGroupNameExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Kiểm tra mã nhóm dân cư đã tồn tại ch
        public JsonResult CheckExistResidentGroupCode(string code, string RESIDENT_GROUP_ID)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(code))
                {
                    ResidentGroupModel residentGroupModel = new ResidentGroupModel()
                    {
                        CODE = code
                    };
                    var model = search(residentGroupModel, 0, string.Empty, true);

                    if (model.Data.Any())
                    {


                        var lstItem = model.Data;
                        foreach (ResidentGroupModel residentGroup in lstItem)
                        {
                            if (!(String.IsNullOrEmpty(RESIDENT_GROUP_ID) || String.IsNullOrWhiteSpace(RESIDENT_GROUP_ID)))
                            {
                                if (!Equals(residentGroup.RESIDENT_GROUP_ID, RESIDENT_GROUP_ID))
                                {
                                    isExist = true;
                                    break;
                                }
                            }
                            else
                            {
                                //Kiem tra truong hop them moi
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    return Json(Resources.Localization.ResidentGroupCodeExist);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục nhóm cư trú - ResidentGroupController";
        }
    }
}